//
// Created by francklinson on 2021/10/4 AT 9:31.
//
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#include <functional>
#include <climits>
#include <string>

using namespace std;

class Solution {
public:
    string licenseKeyFormatting(string s, int k) {
        int n = 0;
        string ans;
        for (char &x: s) {
            if (x != '-') ++n;
        }
        if (n == 0)
            return ans;
        int first_seg_length = n % k;
        int rest_seg_num = n / k;
        int ptr = 0;// 指向s的指针
        // 第一段
        if (first_seg_length != 0) {
            for (int i = 0; i < first_seg_length; ++i) {
                while (s[i + ptr] == '-')
                    ++ptr;
                ans.push_back(char(toupper(s[i + ptr])));
            }
            ptr += first_seg_length;
            ans.push_back('-');
        }
        // 剩下的各段
        for (int i = 0; i < rest_seg_num; ++i) {
            for (int j = 0; j < k; ++j) {
                while (s[j + ptr] == '-')
                    ++ptr;
                ans.push_back(char(toupper(s[j + ptr])));
            }
            ptr += k;
            ans.push_back('-');
        }
        ans.pop_back(); // 去掉最后一个'-'
        return ans;
    }
};

class Solution2 {
public:
    string licenseKeyFormatting(string s, int k) {
        string ans;
        int cnt = 0;

        for (int i = s.size() - 1; i >= 0; i--) {
            if (s[i] != '-') {
                ans.push_back(toupper(s[i]));
                cnt++;
                if (cnt % k == 0) {
                    ans.push_back('-');
                }
            }
        }
        if (ans.size() > 0 && ans.back() == '-') {
            ans.pop_back();
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

int main() {
    Solution solution;
    cout << solution.licenseKeyFormatting("2-5g-3-j", 2) << endl;
    cout << solution.licenseKeyFormatting("5F3Z-2e-9-w", 4) << endl;
    cout << solution.licenseKeyFormatting("--a-a-a-a--", 2) << endl;
    cout << solution.licenseKeyFormatting("---", 2) << endl;
    return 0;
}

